<template>
  <div class="contentView" v-loading="formLoading" :style="`height:${contentHeight}px`">
    <div class="routeHeader">
      <el-button
        @click="submitForm"
        type="primary"
        :disabled="formLoading"
        v-hasPermi="['technology:drawing-order-task:save']"
        v-show="!formType && [20, 30, 50].includes(formData.dictStatus)"
        >保 存</el-button
      >
      <el-button @click="goBack">关 闭</el-button>
    </div>
    <el-scrollbar :style="`height:${contentHeight - 63}px`">
      <p class="baseTitle">基本信息</p>
      <el-form
        ref="formRef"
        :model="formData"
        :inline="true"
        label-width="150px"
        v-loading="formLoading"
      >
        <el-form-item label="订单号" prop="orderNumber">
          <el-input v-model="formData.orderNumber" placeholder="请输入订单号" disabled />
        </el-form-item>
        <el-form-item label="客户代码" prop="customerCode">
          <el-input v-model="formData.customerCode" placeholder="请输入客户代码" disabled />
        </el-form-item>
        <el-form-item label="任务类型" prop="dictTaskType">
          <el-select v-model="formData.dictTaskType" placeholder="请选择任务类型" disabled>
            <el-option
              v-for="dict in getIntDictOptions('task_type')"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="产品编号" prop="productNumber">
          <el-input v-model="formData.productNumber" placeholder="请输入产品编号" disabled />
        </el-form-item>
        <el-form-item label="产品规格" prop="productStandard">
          <el-input v-model="formData.productStandard" placeholder="请输入产品规格" disabled />
        </el-form-item>
        <el-form-item label="交货日期" prop="deliveryTime">
          <el-date-picker
            v-model="formData.deliveryTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="选择交货日期"
            disabled
          />
        </el-form-item>
        <el-form-item label="下单日期" prop="placeOrderDate">
          <el-date-picker
            v-model="formData.placeOrderDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="选择下单日期"
            disabled
          />
        </el-form-item>
        <el-form-item label="产品制图开始日期" prop="planStartDate">
          <el-date-picker
            v-model="formData.planStartDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="选择产品制图开始日期"
            disabled
          />
        </el-form-item>
        <el-form-item label="产品制图结束日期" prop="planEndDate">
          <el-date-picker
            v-model="formData.planEndDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="选择产品制图结束日期"
            disabled
          />
        </el-form-item>
        <el-form-item label="订单数量" prop="orderQuantity">
          <el-input v-model="formData.orderQuantity" placeholder="请输入订单数量" disabled />
        </el-form-item>
        <el-form-item label="出图类型" prop="dictDrawingType">
          <el-select v-model="formData.dictDrawingType" placeholder="请选择任务类型" disabled>
            <el-option
              v-for="dict in getIntDictOptions('drawing_type')"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="产品类型" prop="drawingComponentId">
          <el-select
            v-model="formData.drawingComponentId"
            filterable
            remote
            reserve-keyword
            :remote-method="getProductType"
            :loading="productTypeLoading"
            class="!w-120px"
            :disabled="formType || (!formType && formData.dictStatus != 20)"
            @change="changeSelectProductType"
          >
            <el-option
              v-for="dict in productTypeList"
              :key="dict.id"
              :label="dict.productType"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <p class="baseTitle">派单详情</p>
      <!-- 20:待指派制图  30：待制图-->
      <el-button
        class="mb-10px"
        @click="addComponent"
        type="primary"
        :disabled="formType || (!formType && formData.dictStatus != 20)"
        >新增行</el-button
      >
      <el-table ref="tableRef" :data="formData.tasks" style="width: 100%" border class="tableView">
        <el-table-column type="index" width="80" label="序号" align="center" />
        <el-table-column
          :property="item.val"
          :label="item.label"
          :min-width="item.width"
          :key="item.val"
          v-for="item in tableTitle"
          align="left"
          header-align="left"
        >
          <template #default="scope">
            <template v-if="['proportion', 'explaind', 'ratedOperatingTime'].includes(item.val)">
              <el-input
                v-nextInput="item.val"
                :name="item.val"
                v-model="scope.row[item.val]"
                :disabled="
                  formType ||
                  (!formType &&
                    formData.dictStatus != 20 &&
                    ['proportion', 'ratedOperatingTime'].includes(item.val)) ||
                  (!formType &&
                    ![20, 30, 50].includes(formData.dictStatus) &&
                    item.val == 'explaind')
                "
                :type="['ratedOperatingTime', 'proportion'].includes(item.val) ? 'number' : 'text'"
              />
            </template>
            <template v-else-if="item.val === 'componentProductId'">
              <el-select
                v-model="scope.row[item.val]"
                :disabled="formType || (!formType && formData.dictStatus != 20)"
              >
                <el-option
                  v-for="dict in productDetailList"
                  :key="dict.id"
                  :label="dict.partType"
                  :value="dict.id"
                />
              </el-select>
            </template>
            <template v-else-if="['jobNumber'].includes(item.val)">
              <el-select
                v-model="scope.row[item.val]"
                filterable
                remote
                reserve-keyword
                :remote-method="
                  (e) => {
                    getSelectDesignersList(e, scope.$index)
                  }
                "
                :loading="designersLoading"
                class="!w-120px"
                :disabled="formType || (!formType && ![20, 30, 50].includes(formData.dictStatus))"
              >
                <el-option
                  v-for="dict in scope.row.designersList"
                  :key="dict.jobNumber"
                  :label="dict.designerPersonName"
                  :value="dict.jobNumber"
                />
              </el-select>
            </template>
            <template v-else>
              <el-date-picker
                style="width: 180px"
                v-model="scope.row[item.val]"
                type="date"
                value-format="YYYY-MM-DD"
                :placeholder="`选择${item.label}`"
                :disabled="formType || (!formType && formData.dictStatus != 20)"
              />
            </template>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="100" align="left" header-align="left" fixed="right">
          <template #default="scope">
            <el-button
              @click="delCol(scope.$index)"
              type="danger"
              link
              :disabled="formType || (!formType && formData.dictStatus != 20)"
              >移除行</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-scrollbar>
  </div>
</template>
<script setup lang="ts">
   import { getIntDictOptions } from '@/utils/dict'
   import * as DrawingOrderTaskApi from '@/api/technology/drawingOrderTask'
   import * as componentApi from '@/api/componentApi'
   import { useTagsViewStore } from '@/store/modules/tagsView'
   const { t } = useI18n() // 国际化
   const message = useMessage() // 消息弹窗

   const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
   const formData = ref({
     id: undefined,
     orderNumber: undefined,
     customerCode: undefined,
     dictTaskType: undefined,
     productNumber: undefined,
     productStandard: undefined,
     deliveryTime: undefined,
     placeOrderDate: undefined,
     planStartDate: undefined,
     planEndDate: undefined,
     orderQuantity: undefined,
     dictDrawingType: undefined,
     productType: undefined,
     drawingComponentId: undefined
   })
   const formRef = ref() // 表单 Ref

   /**表头 */
   const tableTitle = ref([
     {
       label: ' 部件类型',
       val: 'componentProductId',
       width: 250
     },
     {
       label: '占比(%)',
       val: 'proportion',
       width: 150
     },
     {
       label: '说明',
       val: 'explaind',
       width: 200
     },
     {
       label: '设计员',
       val: 'jobNumber',
       width: 150
     },
     {
       label: '计划开始日期',
       val: 'planStartDate',
       width: 220
     },
     {
       label: '计划结束日期',
       val: 'planEndDate',
       width: 220
     },
     {
       label: '定额工时(天)',
       val: 'ratedOperatingTime',
       width: 150
     }
   ])

   /**修改产品类型 */
   const productDetailList = ref([]) //部件列表
   const changeSelectProductType = async (id: number) => {
     productDetailList.value = await DrawingOrderTaskApi.getProductDetailList(id)
     //产品中文赋值
     formData.value.productType = productTypeList.value.filter((item) => item.id == id)[0].productType
     //自动填充产品类型下的部件数据
     formData.value.tasks = []
     productDetailList.value.map((item) => {
       formData.value.tasks.push({
         partType: item.partType,
         componentProductId: item.id,
         proportion: undefined,
         explaind: formData.value.explaind,
         jobNumber: undefined,
         planStartDate: undefined,
         planEndDate: undefined,
         ratedOperatingTime: undefined,
         designersList: []
       })
     })
   }

   /**移除部件 */
   const delCol = (index:number) => {
    formData.value.tasks.splice(index,1)
   }
   /**新增部件 */
   const addComponent = () => {
     formData.value.tasks.push({
       partType: undefined,
       componentProductId: query.id,
       proportion: undefined,
       explaind: formData.value.explaind,
       jobNumber: undefined,
       planStartDate: undefined,
       planEndDate: undefined,
       ratedOperatingTime: undefined,
       designersList: []
     })
   }

   /** 提交表单 */
   const submitForm = async () => {
     const data = formData.value as unknown as DrawingOrderTaskApi.DrawingOrderTaskVO
     //校验占比之和
     let num = 0
     //校验规则
     const fillRule = ['', undefined, null]
     let isPass = false

     data.tasks.map((item) => {
       if (
         fillRule.includes(item.jobNumber) ||
         fillRule.includes(item.planStartDate) ||
         fillRule.includes(item.planEndDate) ||
         fillRule.includes(item.ratedOperatingTime)
       ) {
         message.error(`数据不能为空`)
         isPass = true
       }
       num += parseFloat(item.proportion)
       //给设计人姓名赋值
       if (!item.designersList.length) {
         message.error('设计人不能为空')
         isPass = true
       }
       if (item.designersList.length) {
         item.designerPersonName = item.designersList.filter(
           (data) => data.jobNumber == item.jobNumber
         )[0].designerPersonName
       }

       if (fillRule.includes(item.componentProductId)) {
         message.error('请选择部件')
         isPass = true
       } else {
         //给部件类型赋值
         item.partType = productDetailList.value.filter(
           (data) => data.id == item.componentProductId
         )[0].partType
       }
     })
     if (num != 100) {
       message.error('占比之合必须为100!')
       return
     }
     if (isPass) {
       return
     }
     console.log(data)
     //计划结束日期不能早于计划开始日期
    for (let i = 0; i < data.tasks.length; i++) {
      const event = data.tasks[i]
      if (event.planEndDate < event.planStartDate) {
        message.error('计划结束日期不能早于计划开始日期')
        return
      }
    }
     formLoading.value = true
     try {
       await DrawingOrderTaskApi.updateDrawingOrderTask(data)
       message.success(t('common.updateSuccess'))
       goBack()
     } finally {
       formLoading.value = false
     }
   }

   /**设计员搜索 */
   const designersLoading = ref(false)
   const getSelectDesignersList = async (keyword: string, index: number) => {
     designersLoading.value = true
     let data = await componentApi.getDesignersList(keyword)
     formData.value.tasks[index].designersList = data
     designersLoading.value = false
   }

   /**返回 */
   const tagsViewStore = useTagsViewStore()
   const route = useRouter() // 路由
   const goBack = async () => {
     //获取当前路由并删除tagView
     tagsViewStore.delView(route.currentRoute.value)
     //跳转列表页
     route.push({
       path: '/technology/technology/drawingProduction/drawingOrderTask'
     })
   }

   /**获取产品类型数据 */
   const productTypeList = ref([]) //产品类型列表
   const productTypeLoading = ref(false)
   const getProductType = async (str: string) => {
     productTypeLoading.value = true
     const data = await componentApi.getComponentDossierList(str)
     productTypeList.value = data
     productTypeLoading.value = false
   }

   /** 初始化 */
   const { query } = useRoute() // 路由的查询
   const formType = ref(false) //是否可编辑
   const contentHeight = ref(0)
   onMounted(async () => {
     formLoading.value = true
     //edit:编辑 look:查看
     formType.value = query.type == 'edit' ? false : true

     if (query.id) {
       const res = await DrawingOrderTaskApi.getDrawingOrderTask(query.id)
       if (res.productType) {
         await getProductType(res.productType)
         await changeSelectProductType(res.drawingComponentId)
       }

       res.tasks.map((item, index) => {
         getSelectDesignersList(item.designerPersonName, index)
       })

       formData.value = res
     }
     contentHeight.value = document.body.clientHeight - 127
     formLoading.value = false
   })
</script>
<style lang="scss" scoped>
   .routeHeader {
     width: 100%;
     border-bottom: 1px solid #969696;
     display: flex;
     align-items: center;
     padding: 10px 0;
   }
   .baseTitle {
     font-weight: bold;
     padding: 20px 0;
   }
   .tableView {
     :deep(.el-input__wrapper) {
       box-shadow: 0 0 0 0px var(--el-input-border-color, var(--el-border-color)) inset;
       cursor: default;
       .el-input__inner {
         cursor: default !important;
         text-align: left;
       }
     }
   }
</style>